import { userInfoApi } from '@/api/auth'
import { getAuth } from '@/common/utils/storage'

export const useUserStore = defineStore('user', {
  state: () => ({
    id: null,         // 数字主键
    userid: '',       // 业务ID（字符串）
    nickname: '',
    avatar: '',
    sex: '',
    online: '',
    email: '',
    last_at: '',
    status: '',
    createdAt: '',
    token: '',
    expireAt: ''
  }),
  actions: {
    async getUserInfo() {
      try {
        const localAuth = getAuth();
        if (localAuth?.userInfo) {
          this.$state = {
            ...this.$state,
            ...localAuth.userInfo,
            online: true
          };
          // 如果本地存储有完整的用户信息,直接返回,不请求API
          if (this.$state.id && this.$state.userid && this.$state.nickname && this.$state.email) {
            return this.$state;
          }
        }
        // 本地没有完整信息时才请求API
        const r = await userInfoApi();
        if (r) {
          this.$state = {
            ...this.$state,
            ...r.data,
            online: true
          };
          console.log('从API更新后的用户store:', this.$state)
        }
        return this.$state;
      } catch (error) {
        console.error('获取用户信息失败:', error);
        return this.$state;
      }
    },
    clear() {
      this.$state = {
        id: null,     // 清空时也要重置数字主键
        userid: '',   // 清空业务ID
        nickname: '',
        avatar: '',
        sex: '',
        online: '',
        email: '',
        last_at: '',
        status: '',
        createdAt: '',
        token: '',
        expireAt: ''
      };
    }
  }
})
